jQuery(document).ready(function($){

    /*
     * REGISTER FUNCTIONS
     */
    $('#add_new_water_record').click(function(e) {
        e.preventDefault();
        var row = $('#hidden_water').clone(true);
        jQuery('#water_container').append(row.contents());
    });
    $('#save_water_record').click(function(e) {
        e.preventDefault();
        
        var counter = $("#form-water input[name='counter']").length;
        
        var subtipo_array = new Array(counter);
        $( "#form-water input[name='subtipo']" ).each(function( index ) {
            subtipo_array[index] = $(this).val();
        });
        
        var mes_array = new Array(counter);
        $( "#form-water input[name='mes']" ).each(function( index ) {
            mes_array[index] = $(this).val();
        });
        
        var cantidad_array = new Array(counter);
        $( "#form-water input[name='cantidad']" ).each(function( index ) {
            cantidad_array[index] = $(this).val();
        });
        
        var precio_array = new Array(counter);
        $( "#form-water input[name='precio']" ).each(function( index ) {
            precio_array[index] = $(this).val();
        });
        
        $.post( "/api/update_user_data/",
        { 
            func:       "updateConsumption", 
            tipo:       1,
            subtipo:    subtipo_array,
            year:       $("#form-water input[name='year']").val(),
            mes:        mes_array,
            cantidad:   cantidad_array,
            precio:     precio_array
        },
        function(data) {
            $('#water_save_message').html(data.message);
        });
    });
    
    $('#add_new_electricity_record').click(function(e) {
        e.preventDefault();
        var row = $('#hidden_electricity').clone(true);
        jQuery('#electricity_container').append(row.contents())
    });
    $('#save_electricity_record').click(function(e) {
        e.preventDefault();
        var counter = $("#form-electricity input[name='counter']").length;
        
        var subtipo_array = new Array(counter);
        $( "#form-electricity input[name='subtipo']" ).each(function( index ) {
            subtipo_array[index] = $(this).val();
        });
        
        var mes_array = new Array(counter);
        $( "#form-electricity input[name='mes']" ).each(function( index ) {
            mes_array[index] = $(this).val();
        });
        
        var cantidad_array = new Array(counter);
        $( "#form-electricity input[name='cantidad']" ).each(function( index ) {
            cantidad_array[index] = $(this).val();
        });
        
        var precio_array = new Array(counter);
        $( "#form-electricity input[name='precio']" ).each(function( index ) {
            precio_array[index] = $(this).val();
        });
        
        $.post( "/api/update_user_data/",
        { 
            func:       "updateConsumption", 
            tipo:       2,
            subtipo:    subtipo_array,
            year:       $("#form-electricity input[name='year']").val(),
            mes:        mes_array,
            cantidad:   cantidad_array,
            precio:     precio_array
        },
        function(data) {
            $('#electricity_save_message').html(data.message);
        });
    });
    
    $('#add_new_gas_record').click(function(e) {
        e.preventDefault();
        var row = $('#hidden_gas').clone(true);
        jQuery('#gas_container').append(row.contents());
    });
    $('#save_gas_record').click(function(e) {
        e.preventDefault();
        var counter = $("#form-gas input[name='counter']").length;
        
        var subtipo_array = new Array(counter);
        $( "#form-gas input[name='subtipo']" ).each(function( index ) {
            subtipo_array[index] = $(this).val();
        });
        
        var mes_array = new Array(counter);
        $( "#form-gas input[name='mes']" ).each(function( index ) {
            mes_array[index] = $(this).val();
        });
        
        var cantidad_array = new Array(counter);
        $( "#form-gas input[name='cantidad']" ).each(function( index ) {
            cantidad_array[index] = $(this).val();
        });
        
        var precio_array = new Array(counter);
        $( "#form-gas input[name='precio']" ).each(function( index ) {
            precio_array[index] = $(this).val();
        });
        
        $.post( "/api/update_user_data/",
        { 
            func:       "updateConsumption", 
            tipo:       3,
            subtipo:    subtipo_array,
            year:       $("#form-electricity input[name='year']").val(),
            mes:        mes_array,
            cantidad:   cantidad_array,
            precio:     precio_array
        },
        function(data) {
            $('#fuel_save_message').html(data.message);
        });
    });
    

       
    /*
     * PROFILE FUNCTIONS
     */
       
    //Edit Sector and Subsector 

    $('#edit_number_company_sector').click(function(e){
        e.preventDefault();
        $("#company_sector_dynamic").removeClass("hidden");
        $("#company_sector_static").addClass("hidden");
        $('#company-sector-year-selector option:last').attr('selected','selected');
        company_sector_load_months_and_sector_subsector();
    });
    $('#company_sector_cancel').click(function(e){
        e.preventDefault();
        $("#company_sector_static").removeClass("hidden");
        $("#company_sector_dynamic").addClass("hidden");
    }); 
           
    var company_sector_load_months = function(e){ 
        $.blockUI({ message: '<h1>Cargando...</h1>' });
        $.post( "/api/request_user_data/",
        { 
            func: "getSectorMonths", 
            year: $("#company-sector-year-selector").val()
        },
        function(data) {
            if(data.status == 'OK'){
                $("#company-sector-month-selector").html(data.content);
            } 
        });
    }   
    
    var company_sector_load_months_and_sector_subsector = function(flag){
        $.blockUI({ message: '<h1>Cargando...</h1>' });
        $.post( "/api/request_user_data/",
        { 
            func: "getSectorMonths", 
            year: $("#company-sector-year-selector").val()
        },
        function(data) {
            if(data.status == 'OK'){
                $("#company-sector-month-selector").html(data.content);
                if(flag==1)$('#company-sector-month-selector option:first').attr('selected','selected');
            } 
        })
        .done(function(){
            $.post( "/api/request_user_data/",
            { 
                func: "getSectors", 
                year: $("#company-sector-year-selector").val(),
                month: $("#company-sector-month-selector").val()
            },
            function(data) {
                if(data.status == 'OK'){
                    $("#company-sector-selector").html(data.content);
                } 
            })
            .done(function(){
                $.post( "/api/request_user_data/",
                { 
                    func: "getSubSectors", 
                    sector: $("#company-sector-selector").val(),
                    year: $("#company-sector-year-selector").val(),
                    month: $("#company-sector-month-selector").val()
                },
                function(data) {
                    if(data.status == 'OK'){
                        $("#company-subsector-selector").html(data.content);
                    } 
                });
            });
        });
    }
    
    var company_sector_load_sector_subsector = function(e){
        $.blockUI({ message: '<h1>Cargando...</h1>' });
        $.post( "/api/request_user_data/",
        { 
            func: "getSectors", 
            year: $("#company-sector-year-selector").val(),
            month: $("#company-sector-month-selector").val()
        },
        function(data) {
            if(data.status == 'OK'){
                $("#company-sector-selector").html(data.content);
            } 
        })
        .done(function(){
            $.post( "/api/request_user_data/",
            { 
                func: "getSubSectors", 
                sector: $("#company-sector-selector").val(),
                year: $("#company-sector-year-selector").val(),
                month: $("#company-sector-month-selector").val()
            },
            function(data) {
                if(data.status == 'OK'){
                    $("#company-subsector-selector").html(data.content);
                } 
            });
        });
    }
    
    var company_sector_load_subsectors = function(e){ 
        $.blockUI({ message: '<h1>Cargando...</h1>' });
        $.post( "/api/request_user_data/",
        { 
            func: "getTodoSubSectors", 
            sector: $("#company-sector-selector").val()
        },
        function(data) {
            if(data.status == 'OK'){
                $("#company-subsector-selector").html(data.content);
            } 
        });
    }   
    
    $('#company-sector-year-selector').ready(function(e){
        $('#company-sector-year-selector option:last').attr('selected','selected');
        company_sector_load_months();
    });
    
    $('#company-sector-year-selector').change(function(e){
        var flag = 1;
        company_sector_load_months_and_sector_subsector(flag);
    });

    $('#company-sector-month-selector').ready(function(company_sector_load_sector_subsector){
        //$('#company-sector-month-selector option:last').attr('selected','selected');
        company_sector_load_sector_subsector();
    });
    
    $('#company-sector-month-selector').change(company_sector_load_sector_subsector);
    
    $('#company-sector-selector').ready(function(company_sector_load_subsectors){
        $('#company-sector-month-selector option:last').attr('selected','selected');
        company_sector_load_subsectors();
    });
    
    $('#company-sector-selector').change(company_sector_load_subsectors);
    
    $('#company_sector_save').click(function(e){
        e.preventDefault();
        $.blockUI({ message: '<h1>Guardando...</h1>' });
        $.post( "/api/update_user_data/",
        { 
            func: "updateSector", 
            year: $("#company-sector-year-selector").val(),
            month: $("#company-sector-month-selector").val(),
            sector: $("#company-sector-selector").val(),
            subsector: $("#company-subsector-selector").val()
        },
        function(data) {
            if(data.status == 'Ok'){
                $("#company_sector_value_static").html($("#company-sector-selector option:selected").text());
                $("#company_subsector_value_static").html($("#company-subsector-selector option:selected").text());
            }else{
                //$("#colaborator_value").val($("#colaborator_value_static").html());
            }
        })
        .fail(function(){
            //$("#colaborator_value").val($("#colaborator_value_static").html());
        })
        .always(function() {
            $("#company_sector_static").removeClass("hidden");
            $("#company_sector_dynamic").addClass("hidden");
        });
    }); 
    
    
    //Edit Products
    $('#edit_product').click(function(e){
        e.preventDefault();
        $("#product_dynamic").removeClass("hidden");
        $("#product_static").addClass("hidden");
        $('#product-year-selector option:last').attr('selected','selected');
        product_load_months_and_product();
    });
    $('#product_cancel').click(function(e){
        e.preventDefault();
        $("#product_static").removeClass("hidden");
        $("#product_dynamic").addClass("hidden");
        $("#product_value").val($("#product_value_static").html());
    });
    
    var product_load_product = function(e){
        $.blockUI({ message: '<h1>Cargando...</h1>' }); 
        $.post( "/api/request_user_data/",
        { 
            func: "getProduct", 
            year: $("#product-year-selector").val(),
            month: $("#product-month-selector").val()
        },
        function(data) {
            if(data.status == 'OK'){
                $("#product_value").val(data.content);
            } 
        });
    }  
    var product_load_months_and_product = function(flag){
        $.blockUI({ message: '<h1>Cargando...</h1>' });
        $.post( "/api/request_user_data/",
        { 
            func: "getProductMonths", 
            year: $("#product-year-selector").val()
        },
        function(data) {
            if(data.status == 'OK'){
                $("#product-month-selector").html(data.content);
                if(flag==1)$('#product-month-selector option:first').attr('selected','selected');
            } 
        })
        .done(function(){
            $.post( "/api/request_user_data/",
            { 
                func: "getProduct", 
                year: $("#product-year-selector").val(),
                month: $("#product-month-selector").val()
            },
            function(data) {
                if(data.status == 'OK'){
                    $("#product_value").val(data.content);
                } 
            });
        });
    }
    
    $('#product-year-selector').ready(function(e){
        $('#product-year-selector option:last').attr('selected','selected');
        product_load_months_and_product();
    });
    $('#product-year-selector').change(function(e){
        var flag = 1;
        product_load_months_and_product(flag);
    });

    $('#product-month-selector').ready(function(e){
        $('#product-month-selector option:last').attr('selected','selected');
        product_load_product();
    })
    $('#product-month-selector').change(product_load_product);

    $('#product_save').click(function(e){
        e.preventDefault();
        $.blockUI({ message: '<h1>Guardando...</h1>' });
        var jqxhr = $.post( "/api/update_user_data/",
        { 
            func: "updateProduct", 
            year: $("#product-year-selector").val(),
            month: $("#product-month-selector").val(),
            value: $("#product_value").val()
        },
        function(data) {
            var currentTime = new Date();
            var currentYear = currentTime.getFullYear();
            var currentMonth = currentTime.getMonth() + 1;
            
            if(currentYear == $("#product-year-selector").val() && currentMonth == $("#product-month-selector").val()){
                $("#product_value_static").html($("#product_value").val());
            }else{
                $("#product_value").val($("#product_value_static").html());
            }
        })
        .fail(function(){
            $("#product_value").val($("#product_value_static").html());
        })
        .always(function() {
            $("#product_static").removeClass("hidden");
            $("#product_dynamic").addClass("hidden");
        });
        
    });       
    
       
    //Edit Colaborator
    $('#edit_number_colaborator').click(function(e){
        e.preventDefault();
        $("#colaborator_dynamic").removeClass("hidden");
        $("#colaborator_static").addClass("hidden");
        $('#colaborator-year-selector option:last').attr('selected','selected');
        colaborator_load_months();
    });
    $('#colaborator_cancel').click(function(e){
        e.preventDefault();
        $("#colaborator_static").removeClass("hidden");
        $("#colaborator_dynamic").addClass("hidden");
        $("#colaborator_value").val($("#colaborator_value_static").html());
    });

    var colaborator_load_months = function(e){ 
        $.blockUI({ message: '<h1>Cargando...</h1>' });
        $.post( "/api/request_user_data/",
        { 
            func: "getWorkersMonths", 
            year: $("#colaborator-year-selector").val()
        },
        function(data) {
            if(data.status == 'OK'){
                $("#colaborator-month-selector").html(data.content);
                //$('#colaborator-month-selector option:first').attr('selected','selected');
            } 
        });
    }
    var colaborator_load_number = function(e){
        $.blockUI({ message: '<h1>Cargando...</h1>' });
        $.post( "/api/request_user_data/",
        { 
            func: "getWorkersNumber", 
            year: $("#colaborator-year-selector").val(),
            month: $("#colaborator-month-selector").val()
        },
        function(data) {
            if(data.status == 'OK'){
                $("#colaborator_value").val(data.content);
            } 
        });
    }  
    var colaborator_load_months_and_number = function(e, pyear){
        $.blockUI({ message: '<h1>Cargando...</h1>' });
        $.post( "/api/request_user_data/",
        { 
            func: "getWorkersMonths", 
            year: $("#colaborator-year-selector").val()
        },
        function(data) {
            if(data.status == 'OK'){
                $("#colaborator-month-selector").html(data.content);
                $('#colaborator-month-selector option:first').attr('selected','selected');
            } 
        })
        .done(function(){
            $.post( "/api/request_user_data/",
            { 
                func: "getWorkersNumber", 
                year: $("#colaborator-year-selector").val(),
                month: $("#colaborator-month-selector").val()
            },
            function(data) {
                if(data.status == 'OK'){
                    $("#colaborator_value").val(data.content);
                } 
            });
        });
    }
    
    $('#colaborator-year-selector').ready(function(e){
        $('#colaborator-year-selector option:last').attr('selected','selected');
        colaborator_load_months();
    });
    $('#colaborator-year-selector').change(function(e){
        colaborator_load_months_and_number();
    });

    $('#colaborator-month-selector').ready(function(colaborator_load_number){
        $('#colaborator-month-selector option:last').attr('selected','selected');
        colaborator_load_number();
    })
    $('#colaborator-month-selector').change(colaborator_load_number);

    $('#colaborator_save').click(function(e){
        e.preventDefault();
        $.blockUI({ message: '<h1>Guardando...</h1>' });
        var jqxhr = $.post( "/api/update_user_data/",
        { 
            func: "updateColaborators", 
            year: $("#colaborator-year-selector").val(),
            month: $("#colaborator-month-selector").val(),
            value: $("#colaborator_value").val()
        },
        function(data) {
            
            var currentTime = new Date();
            var currentYear = currentTime.getFullYear();
            var currentMonth = currentTime.getMonth() + 1;
            
            if(currentYear == $("#colaborator-year-selector").val() && currentMonth == $("#colaborator-month-selector").val()){
                $("#colaborator_value_static").html($("#colaborator_value").val());
            }else{
                $("#colaborator_value").val($("#colaborator_value_static").html());
            }
            
        })
        .fail(function(){
            $("#colaborator_value").val($("#colaborator_value_static").html());
        })
        .always(function() {
            $("#colaborator_static").removeClass("hidden");
            $("#colaborator_dynamic").addClass("hidden");
        });
        
    });
    
    
    //Edit inventory
    var temp_inventory = {};
    $("#edit_inventory").click(function(e){
        e.preventDefault();
        temp_inventory = {};
        $("#inventory_error_message").addClass("hidden");
        $("#inventory_success_message").addClass("hidden");
        $("#inventory_dynamic").removeClass("hidden");
        $("#inventory_static").addClass("hidden");

        $(".inventory_count").parent().addClass("box-input");
        $(".inventory_count").parent().parent().removeClass("number");
        $(".inventory_count").parent().parent().attr("style","display:inline");
        $(".inventory_count").removeAttr("readonly");
        jQuery.each(jQuery(".inventory_count"),function(id,item){
          eval("temp_"+item.name+"="+item.value+";");
        });
        
    });
    $('#inventory_cancel').click(function(e){
        e.preventDefault();
        $("#inventory_static").removeClass("hidden");
        $("#inventory_dynamic").addClass("hidden");
        $(".inventory_count").parent().parent().addClass("number");
         $(".inventory_count").parent().removeClass("box-input");
         $(".inventory_count").parent().parent().removeAttr("style");
         $(".inventory_count").attr("readonly","readonly");
         jQuery.each(temp_inventory,function(id,item){

            $("#inventory_"+id).val(item);
        });

    });
    
    $('#inventory_save').click(function(e){
        $.blockUI({ message: '<h1>Guardando...</h1>' });
        e.preventDefault();
        $("#inventory_error_message").addClass("hidden");
        $("#inventory_success_message").addClass("hidden");
        
        custom_inventory = {};
        var customized_items = jQuery("#customized-items .customized-item");
        if(customized_items.length > 0){
            customized_items.each(function(index) {
                var customized_item = new Object();
                customized_item.name = $(this).find(".name input").attr("value");
                customized_item.value = $(this).find(".qty input").attr("value");
                customized_item.type = $(this).find(".type .select-input").val();
                custom_inventory[index] = customized_item;
            });
        }
        
        inventory = {};
        jQuery.each(jQuery(".inventory_count"),function(id,item){
            eval(item.name+"="+item.value+";");
        });
        $.post( "/api/update_user_data/",
        { 
            func: "updateInventory",
            inventory:  inventory,
            custom_inventory : custom_inventory
        },
        function(data) {

            if(data.status == 'Ok'){
                
                location.reload();
                
                /*$(".inventory_count").addClass("noedit");
                $("#inventory_success_message").removeClass("hidden");
                $("#inventory_success_message").html(data.message);
                $("#inventory_static").removeClass("hidden");
                $("#inventory_dynamic").addClass("hidden");
                $(".inventory_count").parent().parent().addClass("number");
                $(".inventory_count").parent().removeClass("box-input");
                $(".inventory_count").parent().parent().removeAttr("style");
                $(".inventory_count").attr("readonly","readonly"); */              
                
            }else{
                $("inventory_error_message").removeClass("hidden");
                $("#inventory_error_message").html(data.message);
            }
        })
        .fail(function(){
            $("#edit_inventory_message").html('No se pudo actualizar el inventario');
            $("#inventory_error_message").removeClass("hidden");
        });
        
    });
    
    $('#inventory_add').click(function(e){
        e.preventDefault();
        var row = $('#customized-items-template').clone(true);
        jQuery('#customized-items').append(row.contents());
    });
    
    //Edit Email
    $('#edit_email').click(function(e){
        e.preventDefault();
        $("#email_error_message").addClass("hidden");
        $("#email_success_message").addClass("hidden");
        $("#email_dynamic").removeClass("hidden");
        $("#email_static").addClass("hidden");
    });
    $('#email_cancel').click(function(e){
        e.preventDefault();
        $("#email_static").removeClass("hidden");
        $("#email_dynamic").addClass("hidden");
    });
    $('#email_save').click(function(e){
        e.preventDefault();
        $.blockUI({ message: '<h1>Guardando...</h1>' });        
        $("#email_error_message").addClass("hidden");
        $("#email_success_message").addClass("hidden");
        var jqxhr = $.post( "/api/update_user_data/",
        { 
            func:               "updateEmail", 
            oldEmail :          $("#edit_email_old").val(),
            newEmail :          $("#edit_email_new").val(),
            confirmNewEmail :   $("#edit_email_confirm").val()
        },
        function(data) {

            if(data.status == 'Ok'){
                $("#email_value_static").html($("#edit_email_new").val());
                $("#edit_email_new").val("");
                $("#edit_email_confirm").val("");
                //
                $("#email_success_message").removeClass("hidden");
                $("#email_success_message").html(data.message);
                $("#email_static").removeClass("hidden");
                $("#email_dynamic").addClass("hidden");
            }else{
                $("#edit_email_message").html(data.message);
                $("#email_error_message").removeClass("hidden");
                $("#email_error_message").html(data.message);
            }
        })
        .fail(function(){
            $("#edit_email_message").html('No se pudo actualizar el email del usuario');
            $("#email_error_message").removeClass("hidden");
            $("#edit_email_message").html('No se pudo actualizar el email del usuario');
        });
        
    });
    
    //Edit Password
    $('#edit_password').click(function(e){
        e.preventDefault();
        $("#password_error_message").addClass("hidden");
        $("#password_success_message").addClass("hidden");
        $("#password_dynamic").removeClass("hidden");
        $("#password_static").addClass("hidden");
    });
    $('#password_cancel').click(function(e){
        e.preventDefault();
        $("#password_static").removeClass("hidden");
        $("#password_dynamic").addClass("hidden");
    });
    $('#password_save').click(function(e){
        e.preventDefault();
        $.blockUI({ message: '<h1>Guardando...</h1>' });
        $("#password_error_message").addClass("hidden");
        $("#password_success_message").addClass("hidden");
        var jqxhr = $.post( "/api/update_user_data/",
        { 
            func:               "updatePassword", 
            oldPassword :          $("#edit_password_old").val(),
            newPassword :          $("#edit_password_new").val(),
            confirmNewPassword :   $("#edit_password_confirm").val()
        },
        function(data) {

            if(data.status == 'Ok'){
                $("#password_value_static").html($("#edit_email_new").val());
                $("#edit_password_new").val("");
                $("#edit_password_confirm").val("");
                //
                $("#password_success_message").removeClass("hidden");
                $("#password_success_message").html(data.message);
                $("#password_static").removeClass("hidden");
                $("#password_dynamic").addClass("hidden");
            }else{
                $("#edit_password_message").html(data.message);
                $("#password_error_message").removeClass("hidden");
                $("#password_error_message").html(data.message);
            }
        })
        .fail(function(){
            $("#edit_password_message").html('No se pudo actualizar la contraseña del usuario');
            $("#password_error_message").removeClass("hidden");
            $("#edit_password_message").html('No se pudo actualizar la contraseña del usuario');
        });
        
    });
    
    /*
     * VISUALIZATION FUNCTIONS
     */
    $('#filter_select').on("change", function() {
        $("#filter_form").submit();
    });
    
    /*
     * MOBILE FUNCTIONS
     */
    
    //menu mobile
    $('#top-header .menu-toggle').click(function(e){
        e.preventDefault();
        if($(this).hasClass('active')){
            $(this).removeClass("active");
            $('#menu-mobile').slideUp( "slow" );
        }else {
            $(this).addClass("active");
            $('#menu-mobile').slideDown( "slow" );
        }
    });
    
});